﻿using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using Msung.Core.DI;
using Msung.Core.Helper;
using System.Reflection;

namespace Msung.Core.Freesql
{
    public static class RunExtensions
    {

        public static void AddRunExtensions(this IServiceCollection services)
        {
            var assemblyList = RuntimeHelper.GetAllAssemblies();
            foreach (var item in assemblyList)
            {
                var types = item.GetTypes();
                var interfaceTypes = types.Where(oo => oo.IsInterface).Where(oo => oo.Name.EndsWith("MainService"));
                foreach (var interfaceType in interfaceTypes)
                {
                    //注入类型
                    var diType = interfaceType.GetInterfaces().FirstOrDefault(x => x.Name == nameof(ITransient) || x.Name == nameof(IScope) || x.Name == nameof(ISingleton));
                    var implType = types.FirstOrDefault(oo => oo.Name == interfaceType.Name.Substring(1) && !oo.IsInterface && !oo.IsAbstract);
                    if (diType == null || implType == null)
                        continue;

                    switch (diType.Name)
                    {
                        case nameof(ITransient):
                            services.AddTransient(interfaceType, implType);
                            break;
                        case nameof(IScope):
                            services.AddScoped(interfaceType, implType);
                            break;
                        case nameof(ISingleton):
                            services.AddSingleton(interfaceType, implType);
                            break;
                    }
                }
            }
        }
    }
}